package com.junke.question.service.filter;

import com.alibaba.fastjson.JSON;
import com.junke.question.service.common.Response;
import com.junke.question.service.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 认证成功
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    JwtUtil jwtUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        ServletOutputStream outputStream = response.getOutputStream();
        String details = authentication.getDetails().toString();
        String token = jwtUtil.createToken(details);
        response.setHeader("Authorization", token);
        outputStream.write(JSON.toJSONString(Response.ok("success!")).getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }
}
